﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EncuentraloSilverlight.Web.Models;
using System.Data.Linq;

namespace EncuentraloSilverlight.Models
{
    public class CategoryRepository        
    {
        private EncuentraloDataBaseModelDataContext db;


        public CategoryRepository()
        {
            db = new EncuentraloDataBaseModelDataContext();
            DataLoadOptions options = new DataLoadOptions();
            options.LoadWith<Category>(k => k.ProductCategories);
            db.LoadOptions = options;
        }

        //
        // Metodos de consulta

        /// <summary>
        /// retorna todas las categorias
        /// </summary>
        /// <returns></returns>
        public IQueryable<Category> FindAllCategories()
        {
            return db.Categories;
        }

        public IQueryable<Category> FindCategoryByName(string name)
        {
            return from category in db.Categories
                   where category.Name.Equals(name)
                   select category;
        }

        /// <summary>
        /// retorna una categoria segun el id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Category GetCategory(int id)
        {
            return db.Categories.SingleOrDefault(d => d.CategoryID == id);
        }

        //
        // Insert/Delete Methods
        public void Add(Category category)
        {
            db.Categories.InsertOnSubmit(category);
            Save();
        }
        public void Delete(Category category)
        {
            db.ProductCategories.DeleteAllOnSubmit(category.ProductCategories);
            db.Categories.DeleteOnSubmit(category);
            Save();
        }

        //
        // Persistence
        private void Save()
        {
            db.SubmitChanges();
        }



    }
}